package com.mz.ieann.aide.media.audio.view

import android.Manifest
import android.media.AudioManager
import android.util.Log
import android.view.View
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import androidx.activity.compose.setContent
import androidx.core.view.WindowCompat
import com.mz.ieann.aide.R
import com.mz.ieann.aide.base.vm.BaseVMActivity
import com.mz.ieann.aide.databinding.ActivityAudioPlayerBinding
import com.mz.ieann.aide.media.audio.model.AudioViewModel
import com.mz.ieann.aide.utils.PermissionUtil
import com.mz.ieann.dokit.utils.TimeUtil
import com.mz.ieann.doplayer.audio.AudioHelper
import com.mz.ieann.doplayer.audio.listener.ProgressListener
import com.mz.ieann.doplayer.audio.ui.AudioControllerDialog

/**
 * <p>------------------------------------------------------
 * <p>Copyright (C) 2020 wasu company, All rights reserved.
 * <p>------------------------------------------------------
 * <p>
 * <p>
 *
 * @author Created by zhangmz
 * @date on 2023/5/11
 */
class AudioPlayerActivity:
    BaseVMActivity<AudioViewModel, ActivityAudioPlayerBinding>(
    R.layout.activity_audio_player
), ProgressListener {

    /**
     * 音频资源文件assets下文件夹名称
     */
    private val audioDirName = "audio"

    /**
     * assets 目录下文件资源
     */
    private lateinit var assetsFileList: List<String>

    /**
     * 播放资源索引
     */
    private var playIndex = 0

    override fun createBefore() {
        super.createBefore()
        WindowCompat.setDecorFitsSystemWindows(window, false)
    }

    override fun initActivity() {
        volumeControlStream = AudioManager.STREAM_MUSIC

//        checkPermission()

        setContent {
            PermissionUtil.CheckMultiplePermission(
                permissionName = arrayOf(
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.MODIFY_AUDIO_SETTINGS,
                    Manifest.permission.CAMERA,
                    Manifest.permission.CALL_PHONE,
                    Manifest.permission.READ_SMS,
                    Manifest.permission.SEND_SMS,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                ),
                execute = {
                    Log.v("audio_player", "权限申请成功")
                },
                denial = {
                    it.forEach { p ->
                        Log.v("audio_player", "这些权限申请失败,permission:$p")
                    }
                }
            )
        }

        bindListener()
        queryData()

    }

    private fun bindListener(){
        binding.progress.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                binding.tvTimeEnd.text = TimeUtil.formatTimeString(progress.toLong(), TimeUtil.format8)
                binding.tvTimeStart.text = TimeUtil.formatTimeString(progress.toLong(), TimeUtil.format8)
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {  }
            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                AudioHelper.updateProgress(seekBar?.progress?: binding.progress.progress)
            }
        })
    }

    private fun queryData(){
        assetsFileList = assets.list(audioDirName)?.toList()!!
    }

    fun onPlayClick(view: View?){
        when(view?.id){
            R.id.btBack -> finish()
            R.id.btMenu -> {
                AudioControllerDialog.Build.setEqualizerNum(5).show(supportFragmentManager)
            }
            R.id.btRewind -> {
                AudioHelper.updateProgress(binding.progress.progress - binding.progress.max / 20)
            }
            R.id.btForward -> {
                AudioHelper.updateProgress(binding.progress.progress + binding.progress.max / 20)
            }
            R.id.btPlay -> {
                Log.v("audio_player", "isPlaying: ${AudioHelper.isPlaying()}")
                if (AudioHelper.isPlaying()){
                    binding.btPlay.setBackgroundResource(R.drawable.baseline_play_circle_outline)
                    AudioHelper.pause()
                    return
                }
                binding.btPlay.setBackgroundResource(R.drawable.baseline_pause_circle_outline)
                playAudio()
            }
            R.id.btPrevious -> {
                playIndex = if (--playIndex < 0) assetsFileList.size - 1 else playIndex
                AudioHelper.release()
                playAudio()
            }
            R.id.btNext -> {
                playIndex = if (++playIndex > assetsFileList.size - 1) 0 else playIndex
                AudioHelper.release()
                playAudio()
            }
        }
    }

    private fun playAudio(){
        val fileName = "$audioDirName/${assetsFileList[playIndex]}"
        Log.v("audio_player", "playAudio, fileName:$fileName")
        AudioHelper.create(this, assets.openFd(fileName))
            .addListener(this)
            .addVisualizer(binding.visualizerView)
            .prepare(binding.uicontainer)
    }

    override fun updateProgress(duration: Int, position: Int) {
        if (position > duration){ return }
        // 触摸滑动中，不自动修改进度
        if (binding.progress.isPressed){
            return
        }
        binding.progress.max = duration
        binding.progress.progress = position
    }

//    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
//        return super.dispatchKeyEvent(event)
//    }
//
//    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
//        return super.onKeyDown(keyCode, event)
//    }

    override fun onStop() {
        super.onStop()
        AudioHelper.release()
    }

//    private fun checkPermission(){
//        requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO, Manifest.permission.MODIFY_AUDIO_SETTINGS), 1)
//    }
//
//    override fun onRequestPermissionsResult(
//        requestCode: Int,
//        permissions: Array<out String>,
//        grantResults: IntArray
//    ) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
//        if (requestCode != 1){
//            return
//        }
//        permissions.forEach {
//            if (it == Manifest.permission.RECORD_AUDIO){
//                toast("RECORD_AUDIO 权限申请成功")
//            }
//            if (it == Manifest.permission.MODIFY_AUDIO_SETTINGS){
//                toast("MODIFY_AUDIO_SETTINGS 权限申请成功")
//            }
//        }
//    }

}